import {
  build,
  calculate,
  check_shipping,
  create,
  paymentFirst
} from "../../../api/order"
import {
  list
} from '../../../api/address';
import {
  find as findProduct
} from "../../../api/product/"
import {
  find
} from "../../../api/shop"
import {
  submit,
  query
} from '../../../api/payment';
const util = require('../../../utils/util');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    APP_OSSURL_API: app.APP_OSSURL_API,
    safeBottom: Math.abs(app.globalData.hh - (app.globalData.safeArea.bottom || 0)),
    dishesInfo: [{
        name: "名称",
        value: new Array(6).fill("火爆腰花")
      },
      {
        name: "数量",
        value: new Array(6).fill("1")
      },
      {
        name: "价格",
        value: new Array(6).fill(40)
      }
    ],
    date: "2020-12-10",
    time: "lunch",
    showMoreDishes: false,
    showAddressModal: false,
    showConfirmOrderModal: false,
    address: null,
    calculate: null,
    amount: 0,
    chefId: '',
    chefForm: null,
    propsForm: [],
    textareaTitle: '',
    advance: 0,
    couponsType: false,
    couponCodeName: '',
    shopId: '',
    adjust: true,
    showMask: 'none',
    menuSlide: 'none',
    value: "2020-12-31 早餐"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.data.chefId = options.chefId
    this.data.textareaTitle = options.textareaTitle
    this.data.shopId = options.shopId
    this.data.adjust = options.adjust
    this.data.packageNum = options.packageNum

    this.chefClick()
    this.buildClick()
    var nowDate = new Date();
    var year = nowDate.getFullYear(),
      month = nowDate.getMonth() + 1,
      day = nowDate.getDate()
    this.setData({
      "date": `${year}-${month}-${day}`,
      value:`${year}-${("00"+month).substr(-2)}-${("00"+day).substr(-2)} 早餐`,
      packageNum:options.packageNum,
      marketPrice:options.marketPrice,
      formsTitle:options.formsTitle
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 用户信息/修改地址
   */
  alterAddress: function () {
    this.setData({
      showAddressModal: true
    })
  },

  /**
   * 菜品信息/显示更多内容
   */
  showMoreInfo: function () {
    this.setData({
      showMoreDishes: !this.data.showMoreDishes
    })
  },
  /**
   * 修改地址/保存联系地址
   */
  saveAddress: function () {
    this.setData({
      showAddressModal: false
    })
  },
  /**
   * 确认支付/确认订单信息
   */
  confirmOrder: function () {
    // this.setData({
    //   showConfirmOrderModal: true
    // })
    var _this = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    if (_this.data.address == null) {
      wx.hideLoading()
      wx.showToast({
        title: '请选择地址',
      })
    } else {
      _this.checkClick()
    }
  },
  /**
   * 确认支付/取消操作
   */
  cancel: function () {
    this.setData({
      showConfirmOrderModal: false
    })
  },
  /**
   * 确认支付/确认订单信息操作/跳转到确认支付页
   */
  confirmOrderinfo: function () {
    wx.navigateTo({
      url: `../paymentProcess/paymentProcess?orderId=${this.data.orderId}`,
    })
  },

  /**
   * 用餐时间/更改日期
   */
  changeDate: function (e) {
    console.log(e)
    var _this = this
    this.setData({
      date: e.detail.value
    })
  },
  /**
   * 用餐时间/更改时间
   */
  changeTime: function (e) {
    var _this = this
    this.setData({
      time: e.currentTarget.dataset.time
    })
  },

  buildClick() {
    var _this = this
    build({
      shopId: _this.data.shopId
    }).then(res => {
      console.log(res)
      _this.data.calculate = res.data.order
      // debugger
      _this.savedialogClick(_this.data.packageNum)
      _this.loadList()
      _this.findProductClick(res.data.order.itemList[0].productId)
      _this.setData({
        calculate: _this.data.calculate,
      })
    })
  },
  // 获取默认地址
  loadList() {
    var _this = this
    var defaultAddress = []
    list({
      mchId: app.globalData.mchId
    }).then(res => {
      console.log(res)
      if (res.data.data.length > 0) {
        res.data.data.forEach(function (item) {
          if (item.isDefault == true) {
            defaultAddress.push(item)
          }
        })
      }
      if (!util.isNull(defaultAddress)) {
        _this.data.address = defaultAddress[0]
      }
      console.log(_this.data.address)
      console.log('默认地址')
      if (this.data.address != null) {
        _this.data.calculate.address = _this.data.address.address
        _this.data.calculate.receiverId = _this.data.address.id
        _this.data.calculate.areaName = _this.data.address.areaName
        _this.data.calculate.consignee = _this.data.address.consignee
        _this.data.calculate.phone = _this.data.address.phone
      }
      _this.setData({
        address: _this.data.address,
        calculate: _this.data.calculate
      })
      _this.calculateClick(_this.data.calculate)
    }).catch(error => {})
  },
  // 点击切换地址
  addressClick() {
    var _this = this
    wx.navigateTo({
      url: '/pages/member/address/address?type=product',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
          _this.data.address = data.data
          _this.data.calculate.address = _this.data.address.address
          _this.data.calculate.receiverId = _this.data.address.id
          _this.data.calculate.areaName = _this.data.address.areaName
          _this.data.calculate.consignee = _this.data.address.consignee
          _this.data.calculate.phone = _this.data.address.phone
          _this.setData({
            address: _this.data.address,
            calculate: _this.data.calculate
          })
          _this.calculateClick(_this.data.calculate)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
    })
  },
  calculateClick(data) {
    var _this = this
    calculate(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          res.data.order.itemList.forEach(function (item) {
            item.thumbnail = util.thumbnail(item.thumbnail, 115, 115)
          })
          res.data.order.amountPayable = (Number(res.data.order.amountPayable)).toFixed(2)
          this.data.calculate = res.data.order
          this.data.amount = res.data.amount.toFixed(2)
          this.data.advance = (res.data.amount * 0.2).toFixed(2)
          if (!util.isNull(res.data.couponCodeName)) {
            _this.data.couponCodeName = res.data.couponCodeName
            _this.setData({
              couponCodeName: _this.data.couponCodeName
            })
          }
          this.setData({
            calculate: this.data.calculate,
            amount: this.data.amount,
            advance: this.data.advance
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  chefClick() {
    var _this = this
    find(_this.data.shopId).then(res => {
      console.log('打印厨师详情')
      console.log(res)
      _this.data.chefForm = res.data.shop
      _this.setData({
        chefForm: _this.data.chefForm
      })
    })
  },
  findProductClick(id) {
    var _this = this
    findProduct(id).then(res => {
      console.log(res)
      _this.data.propsForm = res.data.meta.props
      _this.setData({
        propsForm: _this.data.propsForm
      })
    })
  },
  quantityClick() {
    this.selectComponent('#dialogNum').appear()
  },
  savedialogClick(data) {
    console.log(data)
    var _this = this
    this.data.calculate.itemList[0].quantity = data
    this.calculateClick(_this.data.calculate)
    this.setData({
      calculate: this.data.calculate
    })
  },
  // 选择支付方式
  changeClick(data) {
    console.log(data)
    var _this = this
    var paymentPluginId = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].paymentPluginId
    if (_this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk == false) {
      if (_this.data.amount != 0) {
        if (paymentPluginId == 'waterTicketPayPlugin' || paymentPluginId == 'couponCodePayPlugin') {
          var amount = 0
          _this.data.calculate.paymentVo.forEach(function (item) {
            amount += Number(item.amount)
            item.amount = 0
            item.chk = false
          })
          amount = Number(amount) + Number(_this.data.amount)
          console.log(amount)
          console.log(_this.data.calculate.paymentVo)
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
          _this.data.amount = amount - _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount
        } else {
          if (_this.data.amount >= _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance) {
            _this.data.amount = (Number(_this.data.amount) - Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance)).toFixed(2)
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          } else {
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.amount
            _this.data.amount = 0
          }
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
        }
      } else {
        _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false;
        wx.showToast({
          icon: "none",
          title: '本商品已无法抵用优惠',
        })
      }
    } else {
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false
      _this.data.amount = Number(_this.data.amount) + Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount)
      console.log(_this.data.amount)
      _this.data.amount = _this.data.amount.toFixed(2)
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = 0
    }
    _this.setData({
      calculate: _this.data.calculate,
      amount: _this.data.amount
    })
  },
  couponsClick() {
    if (this.data.calculate.discount == 0 && this.data.calculate.couponDiscount == 0) {
      wx.showToast({
        title: '暂无优惠',
        icon: "none",
      })
    } else {
      this.data.couponsType = true
      this.setData({
        couponsType: this.data.couponsType
      })
    }
  },
  completecoupons: function (e) {
    console.log(e)
    this.data.couponsType = false
    this.setData({
      coupons: e.detail.completecoupons,
      couponsType: this.data.couponsType
    })
  },
  cenclecoupons() {
    this.data.couponsType = false
    this.setData({
      couponsType: this.data.couponsType
    })
  },
  checkClick() {
    var _this = this
    _this.data.calculate.memo = _this.data.textareaTitle
    check_shipping(_this.data.calculate, {
      receiverId: _this.data.calculate.receiverId
    }).then(
      res => {
        console.log(res)
        if (res.data.length == 0) {
          _this.createClick()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '您已经超出配送范围',
          })
        }
      }
    ).catch(error => {
      wx.hideLoading()
    })
  },
  // 创建订单
  createClick() {
    var _this = this
    if (_this.data.time == '早餐') {
      _this.data.calculate.estimateDate = Date.parse(new Date(_this.data.date + ' ' + "9:00"));
    } else if (_this.data.time == '午餐'){
      _this.data.calculate.estimateDate = Date.parse(new Date(_this.data.date + ' ' + "12:00"));
    } else {
      _this.data.calculate.estimateDate = Date.parse(new Date(_this.data.date + ' ' + "18:00"));
    }
    _this.data.calculate.orderType = 1
    _this.data.calculate.chefId = _this.data.chefId
    _this.data.calculate.shopId = _this.data.shopId
    _this.data.calculate.allocateChef = _this.data.adjust
    create(_this.data.calculate, {
      shippingMethod: _this.data.shippingMethod,
    }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.orderId = res.data.id
          if (res.data.paymentStatus == 1) {
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
            })
          } else {
            _this.paymentClick(res)
          }
        }
      }
    ).catch(error => {
      wx.hideLoading()
    })
  },
  paymentClick(data) {
    var _this = this
    paymentFirst(data.data.id).then(res => {
      if (res.type == 'success') {
        _this.submitClick(res)
      } else {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.hideLoading()
    })
  },
  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            setTimeout(function () {
              _this.queryClick()
            }, 100);
          },
          'fail': function (red) {
            wx.showToast({
              icon: "none",
              title: '支付失败',
            })
            wx.redirectTo({
              url: '/pages/order/order/details?id=' + _this.data.orderId,
            })
          }
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: '支付失败',
      })
      wx.redirectTo({
        url: '/pages/order/order/details?id=' + _this.data.orderId,
      })
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.redirectTo({
          url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
        })
      }
    }).catch(error => {
      wx.redirectTo({
        url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
      })
    })
  },
  /**
   * 更改用餐时间
   */
  dinerTimeChoose: function () {
    this.setData({
      showMask: 'dinerTimeMask',
    })
    setTimeout(() => {
      this.setData({
        menuSlide: 'dinerTimeMask'
      })
    }, 550)
  },
  maskclick() {
    this.setData({
      menuSlide: 'none'
    })
    setTimeout(() => {
      this.setData({
        showMask: 'none'
      })
    }, 550)
  },
  handleChange(e) {
    console.log(e)
    this.setData({
      value: e.detail.date,
      date: e.detail.orderDate.date,
      // TODO time为lunch ??
      time:e.detail.orderDate.time
    })
  },
  noteEdit() {
    wx.navigateTo({
      url: `/pages/cook/orderNote/orderNote?textareaTitle=${this.data.textareaTitle}`,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptOrderNote: ({textareaTitle}) =>{
          // debugger
          this.setData({
            textareaTitle:textareaTitle
          })
          console.log(orderNote)
        },
      }
    })
  }
})